import Vuex from 'vuex';
import Vue from 'vue';
import { getUserInfoByToken } from '../api/user';
Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    authorization: '',
    username: '',
    topicNum: 0,
    avatar_url: '',
    user_id: '',
    user_level: '',
  },
  mutations: {
    saveUserInfo(state, params) {
      if (params.token) {
        state.authorization = params.token;
      }
      state.username = params.username;
      state.topicNum = params.topic.length;
      state.avatar_url = params.avatar_url;
      state.user_id = params.user_id;
      state.user_level = params.user_level;
    },
    putInfoToLocal(state) {
      sessionStorage.setItem('authorization', state.authorization);
    },
    getInfoFromLocal(state) {
      state.authorization = sessionStorage.getItem('authorization');
    },
    quitLogin(state) {
      for (const key in state) {
        state[key] = '';
      }
      sessionStorage.removeItem('authorization');
    },
    changeAvatarUrl(state, url) {
      state.avatar_url = url;
    },
  },
  actions: {
    async getUserInfo({ commit, state }) {
      commit('getInfoFromLocal');
      const res = await getUserInfoByToken(state.authorization);
      if (res.code) {
        if (res.data.state == 1) {
          commit('saveUserInfo', res.data);
        }
      } else {
        commit('quitLogin');
      }
    },
  },
});

export default store;
